from random import randint

from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection

from meiduo_mall.libs.yuntongxun.sms import CCP
from threading import Thread
from celery_tasks.sms.tasks import send_sms_code

# def send_sms_code():
#     ccp = CCP()
#     ccp.send_template_sms(mobile, [sms_code, '5'], 1)



class SMS_CODEView(APIView):
    """
           发送短信

           """
    def get(self,request,mobile):

        # 判断时间间隔是否在60秒内
        conn = get_redis_connection('sms_code')
        flag = conn.get('sms_code_flag_%s'% mobile)
        if flag:
            return Response({'error':'请求过于频繁'},status=402)
        # 1.获取手机号
        #2.生成短信验证码
        sms_code = '%06d' % randint(0,999999)
        #3.在redis中存储真实短信验证码
        # 生成管道
        pl = conn.pipeline()
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        pl.setex('sms_code_flag_%s'% mobile,60,2)
        # 连接在redis传递数据
        pl.execute()
        #4.发送短信验证码
        # ccp = CCP()
        # ccp.send_template_sms(mobile,[sms_code,'5'],1)
        # t = Thread(target=send_sms_code,args=(mobile,sms_code))
        # t.start()
        # celery调用
        send_sms_code.delay(mobile,sms_code)
        #5.返回结果
        return  Response({'message':'ok'})